<script setup>
import {
  getLws,
  getLwsPage,
  getQks,
  getQksPage,
  getTplLws,
  getTplQks,
  insertTplQkRelation,
  linkRelation,
  unlinkRelation,
} from '@/api/tpl.js';
import { ref } from 'vue';
import { useGlobalAbility } from '@/mixins/getGlobalAbility.js';

const props = defineProps({
  title: {
    type: String,
    default: '',
  },
  type: {
    type: String,
    default: 'paper',
  },
  tplCode: {
    type: String,
    default: '',
  },
});
const emits = defineEmits(['close']);
const { $message } = useGlobalAbility();

// 关闭弹窗
function closeDialog() {
  emits('close');
}
// 关联内容
// 获取关联列表
const relateList = ref([]);
const pageSize = ref(10);
const currentPage = ref(1);
const total = ref(0);
const content = ref('');
async function getRelateList() {
  const api = props.type === 'paper' ? getLwsPage : getQksPage;
  const returnData = await api({
    tplCode: props.tplCode,
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    content: content.value,
  });
  if (returnData?.code === 200) {
    relateList.value = returnData.rows;
    total.value = returnData.total;
  }
}
getRelateList();
function paginationChange() {
  getRelateList();
}
// 设置关联
async function setRelate(row) {
  const api = row.link === 1 ? linkRelation : unlinkRelation;
  const returnData = await api({
    tag: props.type === 'paper' ? '学校' : '期刊',
    tplCode: props.tplCode,
    qkLwId: row.id,
  });
  if (returnData?.code === 200) {
    $message.success('操作成功');
    await getRelateList();
  } else {
    $message.error(returnData?.msg);
  }
}
</script>

<template>
  <el-dialog :model-value="true" :title="title" @close="closeDialog" class="relate-content-dialog">
    <el-form size="small" inline>
      <el-form-item :label="`${type === 'paper' ? '学校' : '期刊'}名称`">
        <el-input
          v-model="content"
          :placeholder="`请输入${type === 'paper' ? '学校' : '期刊'}名称`"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getRelateList">检索</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="relateList" border size="small">
      <el-table-column
        :label="`${type === 'paper' ? '学校' : '期刊'}名称`"
        prop="name"
      ></el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="text" @click="setRelate(row)">
            {{ row.link === 1 ? '关联' : '取消关联' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="global-pagination-box">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @change="paginationChange"
      />
    </div>
  </el-dialog>
</template>

<style scoped lang="less">
@import './relateContent.less';
</style>
